/**
 * 北京钉图互动科技 all right reserver
 */
package com.impress.commons.exception.translate;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;

import com.impress.commons.exception.BaseErrorCodes;
import com.impress.commons.exception.CustomValidateException;
import com.impress.commons.exception.ErrorCodeEntry;
import com.impress.commons.exception.ErrorResponse;
import com.impress.commons.exception.ErrorResponsePortableException;
import com.impress.commons.exception.RawErrorCodeException;

/**
 * @author Wangyi
 * @since 2016年6月23日
 */
public class DefaultErrorResponseTranslator implements ErrorResponseTranslatable {

	private final ExceptionErrorCodeSupplier errorCodeSupplier;

	/**
	 * @param errorCodeSupplier
	 */
	public DefaultErrorResponseTranslator(ExceptionErrorCodeSupplier errorCodeSupplier) {
		super();
		this.errorCodeSupplier = errorCodeSupplier;
	}

	@Override
	public ErrorResponse translate(Throwable exception) {
		if (exception instanceof ErrorResponsePortableException) {
			return ((ErrorResponsePortableException) exception).getErrorResponse();
		}
		if(exception instanceof MethodArgumentNotValidException)
		{
			BindingResult bindingResult = ((MethodArgumentNotValidException)exception).getBindingResult();  
			String errorMesssage = "";  
			for (FieldError fieldError : bindingResult.getFieldErrors()) {  
				errorMesssage += fieldError.getField()+fieldError.getDefaultMessage() + "\n";  
			}  
			ErrorResponse errorResp=new ErrorResponse(BaseErrorCodes.INVALID_ARGS.getCode(), BaseErrorCodes.INVALID_ARGS.getMessage());
			errorResp.setDetail(errorMesssage);
			return  errorResp;
		}
		
		if(exception instanceof CustomValidateException)
		{
			CustomValidateException custException=((CustomValidateException)exception);
			ErrorResponse errorResp=new ErrorResponse(BaseErrorCodes.ARG_VALID_NOT_PASS.getCode(),custException.getValidMsg());
			errorResp.setDetail(custException.getValidDetailMsg());
			return  errorResp;
		}
		ErrorCodeEntry errorMappingEntry = BaseErrorCodes.UNDEFINED;
		if (exception instanceof RawErrorCodeException) {
			RawErrorCodeException rawErrorException = (RawErrorCodeException) exception;
			errorMappingEntry = rawErrorException.getErrorCode();
		}else {
			errorMappingEntry = errorCodeSupplier.getErrorCode(exception.getClass());
		}
		ErrorResponse errResp = new ErrorResponse(errorMappingEntry);
		if (!errResp.getMessage().equals(exception.getMessage())) {
			errResp.setDetail(exception.getClass().getName() + ": " + exception.getMessage());
		}
		return errResp;
	}

}
